// (function (window) {
	function WondersWeChats() {}
	let wxInitStatus = 0; // 0：未初始化  1：初始化中   2：初始化完毕可以调用微信方法
	let jsSDKList = []; //存储调用微信方法 的列表
	//微信初始化
	WondersWeChats.prototype.wondersWeChatInit = function () {
		let url = window.location.href.split("#")[0],
			that = this;
		//存储缓存
		// this.initUrlStorage();
		wxInitStatus = 1; //状态修改为初始化中
		//先监听jssdk加载初始化完毕，在进行请求接口做微信鉴权处理
		this.loadJS("https://res.wx.qq.com/open/js/jweixin-1.6.0.js", function () {
			//调用封装好的ajax方法
			ajax({
				url: "https://public.hiunihealth.cn/api/jsSDK/healthyHaiNan/platform/pumpstation/jsSDK/createWXSign",
				type: "get",
				data: {
					url: url
				},
				dataType: "json",
				timeout: 10000,
				contentType: "application/json",
				success: function (res) {
					let data = JSON.parse(res).data;
					let jsApiList = ["getLocation", "chooseImage", "scanQRCode", "getLocalImgData"]; //接口列表
					that.wondersAppWeChatConfig(data, jsApiList);
				},
				//异常处理
				error: function (e) {
					console.log("接口请求错误", e);
				}
			});
		});
	};
	//判断jssdk文件有无加载初始化好
	WondersWeChats.prototype.loadJS = function (src, callback) {
		let script = document.createElement("script");
		let head = document.getElementsByTagName("head")[0];
		let loaded;
		script.src = src;
		if (typeof callback === "function") {
			script.onload = script.onreadystatechange = function () {
				if (!loaded && (!script.readyState || /loaded|complete/.test(script.readyState))) {
					script.onload = script.onreadystatechange = null;
					loaded = true;
					callback();
				}
			};
		}
		head.appendChild(script);
	};
	WondersWeChats.prototype.initUrlStorage = function () {
		console.log("initUrlStorage......");
		//微信小程序里需要取url中的参数，再存储
		let weiXinDATA = JSON.parse(decodeURIComponent(this.getQueryVariable("weiXinDATA")));
		let wxData = null;
		if (weiXinDATA) {
			if (typeof weiXinDATA === "string") {
				weiXinDATA = JSON.parse(weiXinDATA);
			}
			if (weiXinDATA && weiXinDATA.length) {
				weiXinDATA.forEach(element => {
					wxData = {
						key: element["key"],
						value: element["value"],
						method: element["method"] ? element["method"] : "set"
					};
					this.setNativeStorage(wxData);
				});
			}
		}
	};
	WondersWeChats.prototype.getQueryVariable = function (variable) {
		let query = window.location.href.split("?");
		let vars = query[1] && query[1].split("&");
		if (vars && vars.length) {
			for (let i = 0; i < vars.length; i++) {
				let pair = vars[i].split("=");
				if (pair[0] == variable) {
					return pair[1];
				}
			}
		}
		return false;
	};
	WondersWeChats.prototype.setNativeStorage = function (data) {
		let key = data.key;
		if (data.method == "set") {
			localStorage[key] = data.value;
		} else if (data.method == "delete") {
			localStorage.removeItem(key);
		}
	};
	//微信鉴权
	WondersWeChats.prototype.wondersAppWeChatConfig = function (data, jsApiList) {
		let that = this;
		wx.config({
			//微信鉴权
			debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
			appId: data.appId, // 必填，公众号的唯一标识
			timestamp: data.timestamp, // 必填，生成签名的时间戳
			nonceStr: data.nonceStr, // 必填，生成签名的随机串
			signature: data.signature, // 必填，签名
			jsApiList: jsApiList // 必填，需要使用的JS接口列表
		});

		wx.ready(function () {
			//微信鉴权后需要立即调用的接口
			wxInitStatus = 2; //状态修改为初始化完毕
			jsSDKList.forEach((element, index) => {
				//循环添加到数组中以便于Promise.all去调用
				that[element.method](element.data).then(res => {
					jsSDKList[index].callback(res);
				});
			});
		});
	};
	WondersWeChats.prototype.wondersWxJsSDKApi = function (method, data, callback) {
		switch (wxInitStatus) {
			case 0: //未初始化
				jsSDKList.push({ method, data, callback });
				if (jsSDKList.length <= 1) {
					this.wondersWeChatInit();
				}
				break;
			case 1: //初始化中
				jsSDKList.push({ method, callback });
				break;
			case 2: //已完成初始化
				this[method](data).then(res => {
					callback(res);
				});
				break;
		}
	};
	//获取地理位置
	WondersWeChats.prototype.getLocation = function (data) {
		return new Promise((resolve, reject) => {
			wx.getLocation({
				type: "wgs84", // 默认为wgs84的gps坐标，如果要返回直接给openLocation用的火星坐标，可传入'gcj02'
				success: function (res) {
					let backResult = {
						code: 0,
						msg: "success",
						longitude: res.longitude,
						latitude: res.latitude
					};
					resolve(backResult);
				}
			});
		});
	};
	// 选择图片
	WondersWeChats.prototype.chooseImage = function (data) {
		let that = this;
		return new Promise((resolve, reject) => {
			let sizeType = ["original"];
			let count = 1;
			if (data.maxCount) {
				count = parseInt(data.maxCount);
			}
			if (data.quality) {
				if (data.quality > 0.5) {
					sizeType = ["original"];
				} else {
					sizeType = ["compressed"];
				}
			}
			wx.chooseImage({
				count: count, // 默认9
				sizeType: sizeType, // 可以指定是原图还是压缩图，默认二者都有
				sourceType: ["album"], // 可以指定来源是相册还是相机，默认二者都有
				success: function (res) {
					let images = [];
					res.localIds.forEach(element => {
						that.getLocalImgData(element).then(res => {
							images.push(res);
						});
					});
					let backResult = {
						code: 0,
						msg: "success",
						images
					};
					resolve(backResult);
				}
			});
		});
	};
	WondersWeChats.prototype.getLocalImgData = function (localId) {
		return new Promise((resolve, reject) => {
			wx.getLocalImgData({
				localId: localId.toString(),
				success: function (res) {
					const localData = res.localData;
					let imageBase64 = "";
					if (localData.indexOf("data:image") == 0) {
						//苹果的直接赋值，默认生成'data:image/jpeg;base64,'的头部拼接
						imageBase64 = localData;
					} else {
						//此处是安卓中的唯一得坑！在拼接前需要对localData进行换行符的全局替换
						//此时一个正常的base64图片路径就完美生成赋值到img的src中了
						imageBase64 = "data:image/jpeg;base64," + localData.replace(/\n/g, "");
					}
					resolve(imageBase64);
				}
			});
		});
	};
	// 调用相机
	WondersWeChats.prototype.camera = function (data) {
		let that = this;
		return new Promise((resolve, reject) => {
			wx.chooseImage({
				count: 1, // 默认9
				sizeType: ["original", "compressed"], // 可以指定是原图还是压缩图，默认二者都有
				sourceType: ["camera"], // 可以指定来源是相册还是相机，默认二者都有
				success: function (res) {
					that.getLocalImgData(res.localIds[0]).then(res => {
						let backResult = {
							code: 0,
							msg: "success",
							avatar: res
						};
						resolve(backResult);
					});
				}
			});
		});
	};
	// 微信扫描二维码
	WondersWeChats.prototype.qrCodeScan = function (data) {
		return new Promise((resolve, reject) => {
			wx.scanQRCode({
				needResult: parseInt(data.needResult), // 默认为0，扫描结果由微信处理，1则直接返回扫描结果，
				scanType: ["qrCode"], // 可以指定扫二维码还是一维码，默认二者都有
				success: function (res) {
					let backResult = {
						code: 0,
						msg: "",
						qrcode: res.resultStr // 当needResult 为 1 时，扫码返回的结果
					};
					resolve(backResult);
				}
			});
		});
	};
	//拨打电话
	WondersWeChats.prototype.callPhone = function (data, callback) {
		if (data.mode === "call") {
			let a = document.createElement("a");
			a.setAttribute("href", "tel:" + data.phoneNumber);
			a.style.display = "block";
			document.body.appendChild(a);
			a.click();
			document.body.removeChild(a);
		}
	};
	//路线导航
	WondersWeChats.prototype.showMapRoute = function (data, callback) {
		let locationMessage = {
			current_location: {
				sName: data.sName, //起点名称, 可不传，默认当前位置 全球贸易之窗
				sLat: data.sLat, //起点纬度, 可不传，默认当前位置20.02207128
				sLon: data.sLon //起点经度, 可不传，默认当前位置 110.33080185
			},
			target_location: {
				tName: data.tName, //终点名称
				tLat: data.tLat, //终点纬度
				tLon: data.tLon //终点经度
			}
		};
		wx.miniProgram.navigateTo({
			url: "/pages/mapNavigation/mapNavigation?locationMessage=" + JSON.stringify(locationMessage)
		});
	};
	//微信支付
	WondersWeChats.prototype.wxPay = function (data, callback) {
		let requestPaymentMessage = {
			wxPayMessage: data.wxPayMessage,
			redirect_url: data.redirect_url
		};
		wx.miniProgram.navigateTo({
			url: "/pages/wxRequestPayment/wxRequestPayment?requestPaymentMessage=" + JSON.stringify(requestPaymentMessage)
		});
	};
	// var wondersWeChat = new wondersWeChats();
	// export default{ wondersWeChat }

	let wondersWeChat = new WondersWeChats();
	export default wondersWeChat;

// 	if (typeof module !== "undefined" && typeof module.exports !== "undefined") {
// 		module.exports = wondersWeChat;
// 	} else {
// 		window.wondersWeChat = wondersWeChat;
// 	}
// })(window);

function ajax(options) {
	options = options || {}; //调用函数时如果options没有指定，就给它赋值{},一个空的Object
	options.type = (options.type || "GET").toUpperCase(); /// 请求格式GET、POST，默认为GET
	options.dataType = options.dataType || "json"; //响应数据格式，默认json

	let params = formatParams(options.data); //options.data请求的数据

	let xhr;

	//考虑兼容性
	if (window.XMLHttpRequest) {
		xhr = new XMLHttpRequest();
	} else if (window.ActiveObject) {
		//兼容IE6以下版本
		xhr = new ActiveXobject("Microsoft.XMLHTTP");
	}

	//启动并发送一个请求
	if (options.type == "GET") {
		xhr.open("GET", options.url + "?" + params, true);
		xhr.send(null);
	} else if (options.type == "POST") {
		xhr.open("post", options.url, true);
		//设置表单提交时的内容类型
		//Content-type数据请求的格式
		xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
		xhr.send(params);
	}

	//    设置有效时间
	setTimeout(function () {
		if (xhr.readySate != 4) {
			xhr.abort();
		}
	}, options.timeout);

	//    接收
	//     options.success成功之后的回调函数  options.error失败后的回调函数
	//xhr.responseText,xhr.responseXML  获得字符串形式的响应数据或者XML形式的响应数据
	xhr.onreadystatechange = function () {
		if (xhr.readyState == 4) {
			let status = xhr.status;
			if ((status >= 200 && status < 300) || status == 304) {
				options.success && options.success(xhr.responseText, xhr.responseXML);
			} else {
				options.error && options.error(status);
			}
		}
	};
}

//格式化请求参数
function formatParams(data) {
	let arr = [];
	for (let name in data) {
		arr.push(encodeURIComponent(name) + "=" + encodeURIComponent(data[name]));
	}
	arr.push(("v=" + Math.random()).replace(".", ""));
	return arr.join("&");
}

